package com.haixinga.commbiz.commons.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.PolicyConditions;
import com.haixinga.commbiz.commons.exception.BizException;
import com.haixinga.commbiz.commons.vo.OssConfigVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Date;

/**
 * @Author terrfly
 * @Date 2020/3/29 15:45
 * @Description 阿里云OSS
 **/
public class AliyunOssKit {

    private static final Logger logger = LoggerFactory.getLogger(AliyunOssKit.class);



    /** 生成oss form格式请求参数， 用作前端通过form形式直接上传到oss；  */
    public static JSONObject genFormParams(String uploadFileName, OssConfigVO ossConfigVO){


        // 创建OSSClient实例。
        OSS client = new OSSClientBuilder().build(ossConfigVO.getOssEndpoint(), ossConfigVO.getOssKeyId(), ossConfigVO.getOssKeySecret());

        try {

            //生成Policy  Post policy 文档： https://help.aliyun.com/document_detail/31988.html?spm=a2c4g.11186623.6.1635.4dbb2e3cCqA5WM
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, ossConfigVO.getOssMaxSize());  //上传文件限制
            String postPolicy = client.generatePostPolicy(new Date(System.currentTimeMillis() + ossConfigVO.getOssExpireTime()), policyConds);


            JSONObject result = new JSONObject();
            result.put("formActionUrl", ossConfigVO.getHttpsHost());  //前端请求的url地址
            result.put("ossFileUrl", ossConfigVO.getHttpsHost() + "/" + uploadFileName);  //当上传成功 oss响应200时， 使用该路径作为文件路径

            //返回前端form表单的参数。 文档： https://help.aliyun.com/document_detail/31988.html?spm=a2c4g.11186623.2.7.b37c436781S3Gx#reference-smp-nsw-wdb
            JSONObject formParams = new JSONObject();
            formParams.put("OSSAccessKeyId",  ossConfigVO.getOssKeyId());  //AccessKeyId
            formParams.put("policy", BinaryUtil.toBase64String(postPolicy.getBytes("utf-8")));  //policy为一段经过UTF-8和base64编码的JSON文本
            formParams.put("Signature", client.calculatePostSignature(postPolicy));   //签名
            formParams.put("key", uploadFileName);  //上传的文件名
            result.put("formPrams", formParams);

            return result;
        } catch (Exception e) {
            throw new BizException("生成oss签名异常！");
        }finally {
            client.shutdown();
        }
    }

    /** 使用oss文件上传  */
    public static void pubObject(String uploadFileName, File uploadFile, OssConfigVO ossConfigVO){

        // 创建OSSClient实例。
        OSS client = new OSSClientBuilder().build(ossConfigVO.getOssEndpoint(), ossConfigVO.getOssKeyId(), ossConfigVO.getOssKeySecret());

        try {
            client.putObject(ossConfigVO.getOssBucketName(), uploadFileName, uploadFile);

        } catch (Exception e) {
            throw new BizException("oss上传失败！");
        }finally {
            client.shutdown();
        }
    }


}
